package com.gvitz.transaction.activities;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.gvitz.transaction.R;
import com.gvitz.transaction.database.webserviceUser;

public class PingActivity extends GVActivity {

	String userEntered;
	String userPin="";
	
	final int PIN_LENGTH = 4;
	boolean keyPadLockedFlag = false;
	Context appContext;
	int count_error;
	

	TextView pinBox0;
	TextView pinBox1;
	TextView pinBox2;
	TextView pinBox3;
	
	TextView [] pinBoxArray;
	
	
	Button button0;
	Button button1;
	Button button2;
	Button button3;
	Button button4;
	Button button5;
	Button button6;
	Button button7;
	Button button8;
	Button button9;
	Button button10;
	Button buttonExit;
	Button buttonDelete;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
	 
		super.onCreate(savedInstanceState);

		//iniciar variables
		setContentView(R.layout.activity_ping);
 
		SharedPreferences prefs= null;
        prefs =  getSharedPreferences("preferencias", Context.MODE_PRIVATE);
        userPin = prefs.getString("pin_usuario","");
		
		appContext = this;
		userEntered = "";
		count_error = Integer.parseInt(prefs.getString("count_block",""));
			

				
		buttonExit = (Button) findViewById(R.id.buttonExit);
		buttonExit.setOnClickListener(new View.OnClickListener() {
		    public void onClick(View v) {
		    
		    	//Exit app
		    	Intent i = new Intent();
		    	i.setAction(Intent.ACTION_MAIN);
		    	i.addCategory(Intent.CATEGORY_HOME);
		    	appContext.startActivity(i); 
		    	finish();
		        
		    }
		    
		    }
		);
		
		
		buttonDelete = (Button) findViewById(R.id.buttonDeleteBack);
		buttonDelete.setOnClickListener(new View.OnClickListener() {
		    public void onClick(View v) {
		    
		    	if (keyPadLockedFlag == true)
		    	{
		    		return;
		    	}
		    	
		    	if (userEntered.length()>0)
		    	{
		    		userEntered = userEntered.substring(0,userEntered.length()-1);
		    		pinBoxArray[userEntered.length()].setText("");
		    	}
		    
		    
		    }
		    
		    }
		);
				
		pinBox0 = (TextView)findViewById(R.id.pinBox0);
		pinBox1 = (TextView)findViewById(R.id.pinBox1);
		pinBox2 = (TextView)findViewById(R.id.pinBox2);
		pinBox3 = (TextView)findViewById(R.id.pinBox3);
		
		pinBoxArray = new TextView[PIN_LENGTH];
		pinBoxArray[0] = pinBox0;
		pinBoxArray[1] = pinBox1;
		pinBoxArray[2] = pinBox2;
		pinBoxArray[3] = pinBox3;
		
	
		View.OnClickListener pinButtonHandler = new View.OnClickListener() {
	
			public void onClick(View v) {
		    	
		 		final SharedPreferences prefs = getSharedPreferences("preferencias",Context.MODE_PRIVATE);
		 		SharedPreferences.Editor editor = prefs.edit();
		    	
		    	if (keyPadLockedFlag == true)
		    	{
		    		return;
		    	}
		    	
		    	Button pressedButton = (Button)v;
	    		
		    	
		    	if (userEntered.length()<PIN_LENGTH)
		    	{
		    		userEntered = userEntered + pressedButton.getText();
		    		
		    		//Update pin boxes
		    		pinBoxArray[userEntered.length()-1].setText("8");
		    		
		    		if (userEntered.length()==PIN_LENGTH)
		    		{
		    			//Check if entered PIN is correct
		    			if (userEntered.equals(userPin))
		    			{    
		    			        
		    			    	editor.putString("app_block","0");
		    			 		editor.putString("count_block","0");
		    			 		editor.commit();		    			        
		    	   			    Intent mainIntent = new Intent(PingActivity.this, MainActivity.class);
		    	   			    PingActivity.this.startActivity(mainIntent);
		    	   			    overridePendingTransition (R.anim.open_next, R.anim.close_main);
		    	   			    PingActivity.this.finish();
		
		    			}
		    			else
		    			{

		    		    	Vibrator vibrator =(Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		    			    vibrator.vibrate(200);
		    				keyPadLockedFlag = true;
		    				count_error = count_error +1;
	    					editor.putString("count_block",Integer.toString(count_error));
		    			 	editor.commit();
		    			 	
		    				if(count_error > 4 ){ 		    					
		    					
		    					    editor.putString("app_block","2");
			    			 	    editor.commit();
			    			 	    
			    			 	    
			            			new AlertDialog.Builder(PingActivity.this)
								    .setTitle(R.string.block_title)
								    .setMessage(R.string.block_description_last)
								    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
								        public void onClick(DialogInterface dialog, int which) { 
								        	
								        	// enviar codigo para desbloquear
								        	webserviceUser w = new webserviceUser(getApplicationContext(), PingActivity.this);
								        	w.SentCode(prefs.getString("id_usuario",""));
								        	
								        }
								     }).show();		
							  	}


		    				else{
		    					if(count_error==4){
		    						Toast.makeText(getApplicationContext(),R.string.block_last, Toast.LENGTH_SHORT).show();	
		    					}
		    					else{
		    						Toast.makeText(getApplicationContext(),getString(R.string.ping_i) +" "+ (5-count_error) +" intentos", Toast.LENGTH_SHORT).show();
		    						}
		    					}
		    				
		    				new LockKeyPadOperation().execute("");
		    				
		    			}
		    		}	
		    	}
		    	else
		    	{
		    		//Roll over
		    		pinBoxArray[0].setText("");
		    		pinBoxArray[1].setText("");
		    		pinBoxArray[2].setText("");
		    		pinBoxArray[3].setText("");
		    		
		    		userEntered = "";		    	
		    		
		    		userEntered = userEntered + pressedButton.getText();		    		
		    		//Update pin boxes
		    		pinBoxArray[userEntered.length()-1].setText("8");
		    		
		    	}
		    	
		    	
		    }
		  };
		
		
		button0 = (Button)findViewById(R.id.button0);
		button0.setOnClickListener(pinButtonHandler);
		
		button1 = (Button)findViewById(R.id.button1);
		button1.setOnClickListener(pinButtonHandler);
		
		button2 = (Button)findViewById(R.id.button2);
		button2.setOnClickListener(pinButtonHandler);
				
		button3 = (Button)findViewById(R.id.button3);
		button3.setOnClickListener(pinButtonHandler);
		
		button4 = (Button)findViewById(R.id.button4);
		button4.setOnClickListener(pinButtonHandler);
		
		button5 = (Button)findViewById(R.id.button5);
		button5.setOnClickListener(pinButtonHandler);
		
		button6 = (Button)findViewById(R.id.button6);
		button6.setOnClickListener(pinButtonHandler);
		
		button7 = (Button)findViewById(R.id.button7);
		button7.setOnClickListener(pinButtonHandler);
		
		button8 = (Button)findViewById(R.id.button8);
		button8.setOnClickListener(pinButtonHandler);
		
		button9 = (Button)findViewById(R.id.button9);
		button9.setOnClickListener(pinButtonHandler);
				
		buttonDelete = (Button)findViewById(R.id.buttonDeleteBack);

        Typeface font = Typeface.createFromAsset( getAssets(), "fonts/fontawesome-webfont.ttf" );

	       buttonDelete.setTypeface(font);
	       buttonExit.setTypeface(font);
		
	}
	
	@Override
	public void onBackPressed() {
		return;
	}
	
	@Override
	public void onResume() {
		super.onResume();
		SharedPreferences prefs= null;
        prefs =  getSharedPreferences("preferencias", Context.MODE_PRIVATE);
		count_error = Integer.parseInt(prefs.getString("count_block",""));
		
		
		
	}
	
	
	
	private class LockKeyPadOperation extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
              for(int i=0;i<2;i++) {
                  try {
                      Thread.sleep(400);
                  } catch (InterruptedException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                  }
              }

              return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {

            //Roll over
                pinBoxArray[0].setText("");
                pinBoxArray[1].setText("");
                pinBoxArray[2].setText("");
                pinBoxArray[3].setText("");

                userEntered = "";

                keyPadLockedFlag = false;
        }

        @Override
        protected void onPreExecute() {
        }
       


        @Override
        protected void onProgressUpdate(Void... values) {
        }
  }
   
}
